package com.example.starter.demo.configuration;

import com.example.starter.demo.component.RedisComponent;
import com.example.starter.demo.properties.RedisProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 自动装配类
 *
 * @author zero
 * @date 2019-11-04
 **/
@Slf4j
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfiguration {

    private final RedisProperties properties;

    /**
     * 当Spring容器中没有JedisPool类的对象时，才调用该方法
     *
     * @return JedisPool
     */
    @Bean
    @ConditionalOnMissingBean(JedisPool.class)
    public JedisPool jedisPool() {
        log.info("redis connect string: {}:{}", properties.getHost(), properties.getPort());
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(properties.getMaxIdle());
        jedisPoolConfig.setMaxTotal(properties.getMaxTotal());
        jedisPoolConfig.setMaxWaitMillis(properties.getMaxWaitMillis());

        String password = properties.getPassword();
        if (password == null || password.length() == 0) {
            return new JedisPool(jedisPoolConfig, properties.getHost(),
                    properties.getPort(), properties.getTimeout());
        }

        return new JedisPool(jedisPoolConfig, properties.getHost(),
                properties.getPort(), properties.getTimeout(), properties.getPassword());
    }

    @Bean
    @ConditionalOnMissingBean(RedisComponent.class)
    public RedisComponent redisComponent(JedisPool jedisPool) {
        return new RedisComponent(jedisPool);
    }
}
